package Excle.POI;

import com.yangjicong.o2o.studey.base.common.enums.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.FileOutputStream;

/**
 * @author 杨纪聪
 * @date 2022年9月24日16:20:27
 * @description POI导出工具类
 *
 * 使用方式: bestpaymall-product
 * com.bestpay.wx.shopping.commons.util.PoiUtil#exportExcelToLocalPath
 *
 */
@Slf4j
public class PoiUtil {

    private PoiUtil() {
        throw new IllegalStateException("Utility class");
    }
    /**
     * 初始化EXCEL(sheet个数和标题)
     *
     * @param titles        标题集合
     * @return XSSFWorkbook对象
     */
    public static SXSSFWorkbook initExcel(String[] titles) {
        // 在内存当中保持 100 行 , 超过的数据放到硬盘中在内存当中保持 100 行 , 超过的数据放到硬盘中
        SXSSFWorkbook wb = new SXSSFWorkbook(100);
        // 根据总记录数创建sheet并分配标题
        SXSSFSheet sheet = wb.createSheet("sheet1");
        SXSSFRow headRow = sheet.createRow(0);
        for (int j = 0; j < titles.length; j++) {
            SXSSFCell headRowCell = headRow.createCell(j);
            headRowCell.setCellValue(titles[j]);
        }
        return wb;
    }


    /**
     * 下载EXCEL到本地指定的文件夹
     *
     * @param wb         EXCEL对象SXSSFWorkbook
     * @param exportPath 导出路径
     */
    public static void downLoadExcelToLocalPath(SXSSFWorkbook wb, String exportPath) {
        try (FileOutputStream fops = new FileOutputStream(exportPath) ){
            wb.write(fops);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != wb) {
                try {
                    wb.dispose();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }



    /**
     * 导出Excel到本地指定路径
     *
     * @param totalRowCount           总记录数
     * @param titles                  标题
     * @param exportPath              导出路径
     */
    public static void exportExcelToLocalPath(Integer totalRowCount, String[] titles, String exportPath, WriteExcelDataDelegated writeExcelDataDelegated){
        // 初始化EXCEL
        SXSSFWorkbook wb = PoiUtil.initExcel(titles);
        // 调用委托类分批写数据
        SXSSFSheet eachSheet = wb.getSheetAt(0);
        int totalPage = totalRowCount/ Constants.PER_WRITE_ROW_COUNT+1;
        for (int j = 1; j <= totalPage; j++) {
            int startRowCount = (j - 1) * Constants.PER_WRITE_ROW_COUNT + 1;
            int endRowCount = startRowCount + Constants.PER_WRITE_ROW_COUNT - 1;
            if(endRowCount>totalRowCount){
                endRowCount = totalRowCount;
            }
            writeExcelDataDelegated.writeExcelData(eachSheet, startRowCount, endRowCount);
        }
        // 下载EXCEL
        PoiUtil.downLoadExcelToLocalPath(wb, exportPath);

    }






}
